package com.fortune.rainshineservice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.entity.ShopEntity;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.query.ShopQuery;
import com.fortune.rainshineservice.util.AddTransCoordinate;
import com.fortune.rainshineservice.mapper.*;
import com.fortune.rainshineservice.service.IShopService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: rainShine
 * @description: 加盟店服务实现类
 * @author: tangyn
 * @create: 2019-03-06
 **/
@Service
//@Transactional(rollbackFor = RuntimeException.class)
public class ShopServiceImpl implements IShopService {
    private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CbmCityMapper cbmCityMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public MsgModel createShop(ShopModel shopModel) {
        try {
            if(shopModel.getUser()!=null && shopModel.getUser().getRoleId() != null && shopModel.getUser().getRoleId() == 5){
                if (StringUtils.isBlank(shopModel.getProvinceCode()) && shopModel.getArea() == 0) {
                    return new MsgModel("省份不能为空！", ResultCode.FAILURE);
                }
                if (StringUtils.isBlank(shopModel.getCityCode())  && shopModel.getArea() == 0) {
                    return new MsgModel("城市不能为空！", ResultCode.FAILURE);
                }
            }

//            if (StringUtils.isBlank(shopModel.getAddress())) {
//                return new MsgModel("请填写门店的地址！", ResultCode.FAILURE);
//            }
            StringBuilder addBuilder = new StringBuilder();
            if(shopModel.getArea()!= null && shopModel.getArea() == 0) {
            	String provinceName = cbmCityMapper.getProvinceNameByCode(shopModel.getProvinceCode());
                addBuilder.append(provinceName);
                String cityName = cbmCityMapper.getCityNameByCode(shopModel.getCityCode());
                addBuilder.append(cityName);
                if (StringUtils.isNotBlank(shopModel.getAreaCode())) {
                    String areaName = cbmCityMapper.getCityNameByCode(shopModel.getAreaCode());
                    addBuilder.append(areaName);
                }
                addBuilder.append(shopModel.getAddress());
                shopModel.setShopPosition(AddTransCoordinate.baiduTranslate(addBuilder.toString().replaceAll(" ","")));
            }

            shopModel.setCreateId(shopModel.getUser().getUserId());
            shopModel.setUpdateId(shopModel.getUser().getUserId());
//            if(shopModel.getAreaCode().isEmpty()) {
//                shopModel.setAreaCode(shopModel.getCityCode());
//                shopModel.setCityCode(shopModel.getProvinceCode());
//            }
            int res = shopMapper.insert(shopModel);
            if (res > 0) {
                return new MsgModel("创建门店成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("创建门店失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("createShop =====> {}", e);
            return new MsgModel("创建门店失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel updateShop(ShopModel shopModel) {
        try {
            if (StringUtils.isBlank(shopModel.getProvinceCode()) && shopModel.getArea() == 0) {
                return new MsgModel("省份不能为空！", ResultCode.FAILURE);
            }
            if (StringUtils.isBlank(shopModel.getCityCode()) && shopModel.getArea() == 0) {
                return new MsgModel("城市不能为空！", ResultCode.FAILURE);
            }
            if (StringUtils.isBlank(shopModel.getAddress())) {
                return new MsgModel("请填写门店的地址！", ResultCode.FAILURE);
            }
            ShopModel oldShop = shopMapper.selectById(shopModel.getId());
            boolean b = !oldShop.getProvinceCode().equals(shopModel.getProvinceCode()) ||
                    !oldShop.getCityCode().equals(shopModel.getCityCode()) ||
                    !oldShop.getAreaCode().equals(shopModel.getAreaCode()) ||
                    !oldShop.getAddress().equals(shopModel.getAddress());
            if (b) {
            	StringBuilder addBuilder = new StringBuilder();
            	if(shopModel.getArea()!= null && shopModel.getArea() == 0) {
            		String provinceName = cbmCityMapper.getProvinceNameByCode(shopModel.getProvinceCode());
                    addBuilder.append(provinceName);
                    String cityName = cbmCityMapper.getCityNameByCode(shopModel.getCityCode());
                    addBuilder.append(cityName);
                    if (StringUtils.isNotBlank(shopModel.getAreaCode())) {
                        String areaName = cbmCityMapper.getCityNameByCode(shopModel.getAreaCode());
                        addBuilder.append(areaName);
                    }
            	}
                addBuilder.append(shopModel.getAddress());
                shopModel.setShopPosition(AddTransCoordinate.baiduTranslate(addBuilder.toString().replaceAll(" ","")));
            }
            shopModel.setUpdateId(shopModel.getUser().getUserId());
//            if(shopModel.getAreaCode().isEmpty()) {
//                shopModel.setAreaCode(shopModel.getCityCode());
//                shopModel.setCityCode(shopModel.getProvinceCode());
//            }
            int res = shopMapper.updateAllColumnById(shopModel);
            if (res > 0) {
                return new MsgModel("更新门店成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("更新门店失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("updateShop =====> {}", e);
            return new MsgModel("更新门店失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel shopList(ParmsModel parm) {
        try {
            //获取登录账号商铺信息，type在这里存放的是shop id
//            ShopModel shopInfo = shopMapper.selectById(parm.getType());
            ShopModel shopInfo = shopMapper.selectById(parm.getShopId());
            List<ShopModel> list;
            if (shopInfo != null) {
                //店铺级别（1：总店，2：招商,3:加盟店）
                //判断为总店
                if (shopInfo.getShopLevel() != 1 && shopInfo.getShopLevel() != 2) {
                    return new MsgModel(ResultCode.FAILURE, "无权限访问该列表");
                }
                if (shopInfo.getShopLevel() == 2) {
                    parm.setUserId(shopInfo.getManagerId());
                }
            }
            parm.setType(3);
            list = shopMapper.getListWithName(parm);
            Integer count = shopMapper.getCounts(parm);
            return new MsgModel(count, list);
        } catch (Exception e) {
            logger.error("shopList =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel delShop(ShopModel shopModel) {
        try {
            boolean rs = shopMapper.deleteById(shopModel.getId()) > 0;
            if (rs) {
                return new MsgModel("删除门店成功！", ResultCode.SUCCESS);
            }
            return new MsgModel("删除门店失败！", ResultCode.FAILURE);
        } catch (Exception e) {
            logger.error("delShop =====> {}", e);
            return new MsgModel("删除门店失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel stopShop(ShopModel shopModel, String userCode) {
        try {
            shopModel.setShopStatus(Byte.valueOf("0"));
            //shopModel.setUpdateId(userCode);
            shopModel.setUpdateTime(new Date());
//            shopMapper.updateShop(shopModel);
            return new MsgModel("停店成功！", ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("stopShop =====> {}", e);
            return new MsgModel("停店失败，请联系技术人员！", ResultCode.FAILURE);
        }
    }

    /**
     * 判断加盟店名称是否已经存在
     *
     * @param shopName
     * @return
     */
    private boolean shopNameExist(String shopName) {
//        int count = shopMapper.findShopNameExist(shopName);
//        if (count > 0) {
//            return true;
//        }
        return false;
    }

    /**
     * 判断加盟店地理坐标是否已经存在
     *
     * @param shopPosition
     * @return
     */
    private boolean shopPositionExist(String shopPosition) {
//        int count = shopMapper.findShopPoistionExist(shopPosition);
//        if (count > 0) {
//            return true;
//        }
        return false;
    }

    @Override
    public List<ShopModel> getShopsByUserId(Integer userId) {
        try {
            return shopMapper.getShopsByUserId(userId);
        } catch (Exception e) {
            logger.error("getShopsByUserId =====> {}", e);
            return null;
        }
    }
    
    @Override
    public List<ShopModel> getShopsByUserId2(Integer userId) {
        try {
            return shopMapper.getShopsByUserId2(userId);
        } catch (Exception e) {
            logger.error("getShopsByUserId =====> {}", e);
            return null;
        }
    }

    @Override
    public List<User> getAllUsersByShopId(Integer shopId) {
        List<User> userList = Lists.newArrayList();
        ShopModel shopModel = shopMapper.selectById(shopId);
        User manager = userMapper.selectById(shopModel.getManagerId());
        userList.add(manager);
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("state", 0);
        List<User> assList = Optional.ofNullable(userMapper.selectList(wrapper)).orElse(Lists.newArrayList());
        userList.addAll(assList);
        return userList;
    }

    @Override
    public MsgModel getShopInfoById(Integer shopId) {
        try {
            ShopEntity shopEntity = shopMapper.selectByIdWithEntity(shopId);
            int count = customerMapper.selectCountByShopId(shopId);
            shopEntity.setCustomerCount(count);
            //获取店员列表
            Wrapper<User> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", shopId);
            List<User> clerks = userMapper.selectList(wrapper);
            shopEntity.setClerks(clerks);
            //获取店长信息
            User mananger = userMapper.selectById(shopEntity.getManagerId());
            shopEntity.setManagerName(mananger.getNickName());
            shopEntity.setManagerPhone(mananger.getPhone());
            shopEntity.setManagerAvatar(mananger.getAvatar());
            return new MsgModel(ResultCode.SUCCESS, shopEntity);
        } catch (Exception e) {
            logger.error("getShopInfoById =====> {}", e);
            return new MsgModel("门店详情异常，请联系技术人员！", ResultCode.FAILURE);
        }

    }

    @Override
    public MsgModel appGetUserShopList(ShopQuery query) {
        List<ShopEntity> list = Optional.ofNullable(shopMapper.selectListByQuery(query)).orElse(Lists.newArrayList());
        return new MsgModel(list.size(), list);
    }

    @Override
    public List<ShopModel> getMapShops(String cityCode) {
        Wrapper<ShopModel> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_status", 1);
        wrapper.eq("shop_level", 3);
        if (StringUtils.isNotBlank(cityCode)) {
            wrapper.eq("city_code", cityCode);
        }
        return shopMapper.selectList(wrapper);
    }

    @Override
    public ShopModel getShopByShopId(Integer shopId) {
        try {
            return shopMapper.selectById(shopId);
        } catch (Exception e) {
            logger.error("getShopByShopId =====> {}", e);
            return null;
        }
    }

    @Override
    public List<ShopModel> getShopByShopLevel(Integer shopLevel) {
        Wrapper<ShopModel> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_level", shopLevel);
        return shopMapper.selectList(wrapper.orderBy("create_time", false));
    }

    @Override
    public List<ShopModel> getShopByMerchantsId(Integer merchantsId) {
        Wrapper<ShopModel> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_level", 3);
        wrapper.eq("merchants_id", merchantsId);
        return shopMapper.selectList(wrapper.orderBy("create_time", false));
    }

    @Override
    public MsgModel getServiceRecordShops(ParmsModel parm) {
        if (parm.getUserId() == null) {
            return new MsgModel("状态异常，请重新登录", ResultCode.FAILURE);
        }
//        if (parm.getShopId() == null) {
//            return new MsgModel("状态异常，请重新登录", ResultCode.FAILURE);
//        }
        Integer roleId = sysUserRoleMapper.getRoleByUser(parm.getUserId());
        if (roleId == null) {
            return new MsgModel("没有权限", ResultCode.FAILURE);
        }
        Page<ShopEntity> page = new Page<>(parm.getPage(), parm.getLimit());
        Map<String,Object> map = new HashMap<>();
        switch (roleId){
            case 4:
                map.put("merchantsId", parm.getUserId());
                break;
            case 5:
                map.put("managerId", parm.getUserId());
                break;
        }
        if(StringUtils.isNotBlank(parm.getSearchValue())){
            map.put("searchValue",parm.getSearchValue());
        }
        List<ShopEntity> shopList = Optional.ofNullable(shopMapper.selectShopsBySearch(map, page)).orElse(Lists.newArrayList());
//        if (StringUtils.isNotBlank(parm.getShopName())) {
//            //boss
//            if (roleId == 2) {
//                shopList = Optional.ofNullable(shopMapper.selectByName(query.getShopName(), null)).orElse(Lists.newArrayList());
//            }
//            //招商
//            if (roleId == 4) {
//                shopList = Optional.ofNullable(shopMapper.selectByName(query.getShopName(), query.getUserId())).orElse(Lists.newArrayList());
//            }
//            if(!shopList.isEmpty()){
//                shopList.forEach(e->{
//                    User mananger = userMapper.selectById(e.getManagerId());
//                    e.setManagerName(mananger.getNickName());
//                    e.setManagerPhone(mananger.getPhone());
//                    e.setManagerAvatar(mananger.getAvatar());
//                });
//            }
//            return new MsgModel(shopList.size(), shopList);
//        }
//        if (roleId == 2) {
//            //获取总店
//            shopList = shopMapper.getShopsByUserId(parm.getUserId());
//            if (!shopList.isEmpty()) {
//                shopList.forEach(e -> e.setParentId(-1));
//            }
//            //获取所有招商
//            List<ShopModel> merchantShops = shopMapper.getMerchantShops();
//            if (!merchantShops.isEmpty()) {
//                for (ShopModel e : merchantShops) {
//                    e.setParentId(shopList.get(0).getId());
//                    //招商下的门店
//                    List<ShopModel> sList = shopMapper.getShopsByMerchantId(e.getManagerId());
//                    if (!sList.isEmpty()) {
//                        for (ShopModel shopModel : sList) {
//                            shopModel.setParentId(e.getId());
//                        }
//                        shopList.addAll(sList);
//                    }
//                }
//                shopList.addAll(merchantShops);
//            }
//        }
//        // 判断为招商
//        if (roleId == 4) {
//            //获取招商自己的shop
//            ShopModel shopModel = shopMapper.selectById(parm.getShopId());
//            shopModel.setParentId(-1);
//            shopList.add(shopModel);
//            //招商下的门店
//            List<ShopModel> sList = shopMapper.getShopsByMerchantId(shopModel.getManagerId());
//            if (!sList.isEmpty()) {
//                for (ShopModel shop : sList) {
//                    shop.setParentId(shopModel.getId());
//                }
//                shopList.addAll(sList);
//            }
//        }
//        //判断为店长
//        if (roleId == 5) {
//            ShopModel shopModel = shopMapper.selectById(parm.getShopId());
//            shopModel.setParentId(-1);
//            shopList.add(shopModel);
//        }
        if(!shopList.isEmpty()){
            shopList.forEach(e->{
                User mananger = userMapper.selectById(e.getManagerId());
                e.setManagerName(mananger.getNickName());
                e.setManagerPhone(mananger.getPhone());
                e.setManagerAvatar(mananger.getAvatar());
            });
        }
        page.setRecords(shopList);
        return new MsgModel(shopList.size(), page.getRecords());
    }

    @Override
    public ShopModel getByShopName(String name) {
        ShopModel model = new ShopModel();
        model.setShopName(name);
        return shopMapper.selectOne(model);
    }

    @Override
    public MsgModel getShopsByMerchants(ParmsModel parm) {
        try{
            Page<ShopEntity> page = new Page<>(parm.getPage(), parm.getLimit());
            Map<String,Object> map = new HashMap<>();
            map.put("merchantsId", parm.getUserId());
            if(StringUtils.isNotBlank(parm.getSearchValue())){
                map.put("searchValue", parm.getSearchValue());
            }
            List<ShopEntity> list = Optional.ofNullable(shopMapper.getAllLevel3Shops(map, page)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e->{
                    User manager = userMapper.selectById(e.getManagerId());
                    e.setManagerName(manager.getNickName());
                    e.setManagerPhone(manager.getPhone());
                    e.setManagerAvatar(manager.getAvatar());
                });
            }
            return new MsgModel(list.size(), list);
        }catch (Exception e){
            logger.error("getShopsByMerchants =====> {}", e);
            return new MsgModel("获取下级门店异常", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getAllLevel3Shops(ParmsModel parm) {
        if(parm.getUserId() == null){
            return new MsgModel("获取登录用户异常", ResultCode.FAILURE);
        }
        Integer roleId = sysUserRoleMapper.getRoleByUser(parm.getUserId());
        if(roleId != 1 && roleId != 2){
            return new MsgModel("无此权限", ResultCode.FAILURE);
        }
        try{
            Page<ShopEntity> page = new Page<>(parm.getPage(), parm.getLimit());
            Map<String,Object> map = new HashMap<>();
            if(StringUtils.isNotBlank(parm.getSearchValue())){
                map.put("searchValue", parm.getSearchValue());
            }
            List<ShopEntity> list = Optional.ofNullable(shopMapper.getAllLevel3Shops(map, page)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e->{
                    User manager = userMapper.selectById(e.getManagerId());
                    e.setManagerName(manager.getNickName());
                    e.setManagerAvatar(manager.getAvatar());
                    e.setManagerPhone(manager.getPhone());
                    User merchants = userMapper.selectById(e.getMerchantsId());
                    e.setMerchantsName(merchants.getNickName());
                });
            }
            page.setRecords(list);
            return new MsgModel(page.getRecords().size(), page.getRecords());
        }catch (Exception e){
            logger.error("getAllLevel3Shops ====> {}", e);
            return new MsgModel("获取所有加盟店列表异常", ResultCode.FAILURE);
        }
    }
}
